from util import *
from threading import Thread
import sys, os
import socket

sys.path.append(os.path.realpath('../server-comm'))
import test_broadcast_send

flags = {
	"register": False,
	"tplId": int(sys.argv[1])
}

class ReceiveBroadcastThread(Thread):
	"""docstring for ReceiveBroadcastThread"""
	def __init__(self, session, flags, port=9001):
		super(ReceiveBroadcastThread, self).__init__()
		self.session = session
		self.flags = flags
		self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
		self.sock.bind(('',port))
		self.isrunning = True
	def run(self):
		while self.isrunning:
			data,addr=self.sock.recvfrom(1024)
			print('Received:',data,'from',addr)
			if data == "register":
				print 'register=true'
				self.flags['register'] = True
	def stop(self):
		self.isrunning = False

def registerChar(session, flags):
	for i in range(0, 2):
		print("Please put you finger on the scanner.")
		test_broadcast_send.send('register-push')
		while True:
			if session.detectFinger():
				if session.saveImage():
					if session.generateTemplate(i):
						print("Finger scan completed. Please remove your finger.")
						test_broadcast_send.send('register-remove')
					else:
						print("Register faild!")
						test_broadcast_send.send('register-error')
						return
				else:
					print("Register faild!")
					test_broadcast_send.send('register-error')
					return
				break
			else:
				continue
		while True:
			if session.detectFinger():
				continue
			else:
				break
	if not session.mergeTemplate(count = 2):
		print("Register faild!")
		test_broadcast_send.send('register-error')
		return
	storeTplId = session.storeChar()
	if storeTplId == None: 
		print("Register faild!")
		test_broadcast_send.send('register-error')
		return
	print("storeTplId: ", storeTplId)
	flags['tplId'] = storeTplId
	print("Register completed!")
	test_broadcast_send.send('register-ok')
	return

def matchChar(session, tplId):
	if not session.loadChar(templateId = tplId, ramId = 1):
		print("System Error!")
		test_broadcast_send.send('authorize-error')
		return False
	# while True:
	if not session.detectFinger():
		print("System Error!")
		test_broadcast_send.send('authorize-error')
		return False
	if session.saveImage():
		if session.generateTemplate(ramId = 0):
			if session.matchChar(): 
				print("Welcome!")
				test_broadcast_send.send('authorize-ok')
				return True
			else:
				print("Sorry. You are not authorized!")
				test_broadcast_send.send('authorize-forbidden')
				return False
		else:
			print("System Error!")
			test_broadcast_send.send('authorize-error')
			return False
	else:
		print("System Error!")
		test_broadcast_send.send('authorize-error')
		return False

if __name__ == "__main__":
	# matchChar(tplId)
	session = Session()
	session.connect()
	rcv_register_thread = ReceiveBroadcastThread(session=session, flags=flags, port=9002)
	rcv_register_thread.start()
	print("Please put you finger on the scanner.")
	while True:
		if flags['register']:
			print 'prepare to register'
			registerChar(session, flags)
			flags['register'] = False
			print("Please put you finger on the scanner.")
		if session.detectFinger():
			matchChar(session, flags['tplId'])
			while True:
				if not session.detectFinger():
					print("Please put you finger on the scanner.")
					break;